package com.cloudcross.ssp.web.back.main.finance;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cloudcross.ssp.base.utils.freemarker.FreemarkerTemplateProcessor;
import com.cloudcross.ssp.base.web.SimpleController;
import com.cloudcross.ssp.common.utils.LangUtil;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.model.Account;
import com.cloudcross.ssp.model.AdvAgent;
import com.cloudcross.ssp.model.AdvBalance;
import com.cloudcross.ssp.model.OperatorBalance;
import com.cloudcross.ssp.service.IAdvAgentService;
import com.cloudcross.ssp.service.IAdvBalanceService;
import com.cloudcross.ssp.service.IOperatorBalanceService;

/**
 * 财务管理相关控制器
 * 
 * @author wuqiang.du
 *
 */
@Controller("back.financeManagementController")
@RequestMapping("/back/main/finance/finance-management")
public class FinanceManagementController extends SimpleController {

    @Autowired
    private IOperatorBalanceService operatorBalanceService;
    @Autowired
    private IAdvBalanceService advBalanceService;
    @Autowired
    private FreemarkerTemplateProcessor templateProcessor;
    @Autowired
    private IAdvAgentService advAgentService;

    @RequestMapping
    public String index(Model model, @RequestParam HashMap<String, Object> paramMap, @RequestParam(defaultValue = "1") int page) {
        int totalRow = 0;
        Pager pager = null;
        pager = new Pager();
        // 统计提现记录的总数
        totalRow = operatorBalanceService.countByParams(paramMap);
        pager.setPage(page);
        pager.setTotalRow(totalRow);
        List<OperatorBalance> operatorBalanceList = operatorBalanceService.findByParams(paramMap, pager);
        model.addAttribute("pager", pager);
        model.addAttribute("operatorBalanceList", operatorBalanceList);
        return page("index");
    }

    /**
     * 财务管理列表页，实现搜索功能时是按交易号进行搜索并且传递过来交易号参数num
     * 
     * @param model
     * @param paramMap
     * @param page
     * @return
     */
    @RequestMapping("/list")
    public String list(Model model, @RequestParam HashMap<String, Object> paramMap, @RequestParam(defaultValue = "1") int page) {
        int totalRow = 0;
        Pager pager = null;
        pager = new Pager();

        // 统计提现记录的总数
        totalRow = operatorBalanceService.countByParams(paramMap);
        pager.setPage(page);
        pager.setTotalRow(totalRow);
        List<OperatorBalance> operatorBalanceList = operatorBalanceService.findByParams(paramMap, pager);

        model.addAttribute("pager", pager);
        model.addAttribute("operatorBalanceList", operatorBalanceList);

        return page("list");
    }

    /**
     * 审核通过操作
     * 
     * @param id
     * @return
     */
    @RequestMapping("/enable")
    public @ResponseBody String enable(Long[] id) {
        if (ArrayUtils.isNotEmpty(id)) {
            // 状态等于3代表审核通过
            operatorBalanceService.updateStatus(LangUtil.array2List(id), 3);
        }
        return OK;
    }

    /**
     * 审核不通过时要把它提现金额加回原账户
     * 
     * @param id
     * @return
     */
    @RequestMapping("/disable")
    public @ResponseBody String disable(Long[] id, String reason) {
        if (ArrayUtils.isNotEmpty(id)) {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("reason", reason);
            paramMap.put("id", id);
            operatorBalanceService.failureAudit(paramMap);
        }
        return OK;
    }

    /**
     * 广告主充值
     * 
     * @param model
     * @param paramMap
     *            用来接收从前端传递过来搜索参数
     * @return
     */
    @RequestMapping("/deposit")
    public String deposit(Model model, @RequestParam HashMap<String, Object> paramMap, @RequestParam(defaultValue = "1") int page) {
        int totalRow = 0;
        Pager pager = null;
        pager = new Pager();
        // 统计充值记录总数
        totalRow = advBalanceService.countByParamsBack(paramMap);
        pager.setPage(page);
        pager.setTotalRow(totalRow);
        List<AdvBalance> advBalanceList = advBalanceService.findByParamsBack(paramMap, pager);

        model.addAttribute("pager", pager);
        model.addAttribute("advBalanceList", advBalanceList);
        return page("deposit");
    }

    /**
     * 充值功能的实现
     * 
     * @param model
     * @param paramMap
     *            接收两个参数一个是要充值的广告主代理商id，一个是要充值的金额
     * @return
     */
    @RequestMapping("/recharge")
    public String recharge(Model model, @RequestParam HashMap<String, Object> paramMap) {

        // 得到当前登录用户
        Account account = getLoginUser();

        // 得到从前端传递过来的代理商id
        Long agentId = Long.parseLong((String) paramMap.get("agentId"));

        // 得到从前端传递过来的充值金额
        Double money = new Double((String) paramMap.get("money"));

        // 得到该代理商的当前余额
        Double balance = advBalanceService.findBalanceByAgentId(agentId);

        // 如果得到的余额为空则将余额变为0
        if (null == balance) {
            balance = 0d;
        }

        // 充值完后的余额
        balance = new Double(balance + money);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmSS");
        AdvBalance advBalance = new AdvBalance();
        advBalance.setAccountId(new Long(account.getId()));
        advBalance.setAgentId(agentId);
        advBalance.setActTime(new Date());
        advBalance.setNum(sdf.format(new Date()));
        advBalance.setCharge(money);
        advBalance.setBalance(balance);

        advBalanceService.add(advBalance);

        return redirect(page("deposit"));
    }

    /**
     * 广告主充值中的撤销操作,执行撤销操作的话，就相当于执行一个充值为该撤销金额负数的充值 前端需要传递一个advBalanceId
     * 
     * @param model
     * @param paramMap
     * @return 如果撤销时账号如果不存在的话，则返回一个false
     */
    @RequestMapping("/backOut")
    public @ResponseBody String backOut(@RequestParam HashMap<String, Object> paramMap) {
        Long advBalanceId = Long.parseLong(String.valueOf(paramMap.get("advBalanceId")));
        AdvBalance advBalance = advBalanceService.findById(advBalanceId);
        AdvAgent advAgent = advAgentService.findById(advBalance.getAgentId());

        // 判断这个账号是否存在，如果不存在则返回false
        if (null == advAgent) {
            return "false";
        } else {
            // 得到该广告主代理商当前的余额
            Double balance = advBalanceService.findBalanceByAgentId(advBalance.getAgentId());
            // 得到这个要撤销的充值金额
            Double money = advBalance.getCharge();
            // 撤销完后的余额
            balance = new Double(balance - money);

            paramMap.put("charge", (-money));
            paramMap.put("balance", balance);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            paramMap.put("num", sdf.format(new Date()));
            paramMap.put("actTime", sdf1.format(new Date()));
            paramMap.put("accountId", getLoginUser().getId());
            paramMap.put("agentId", advBalance.getAgentId());

            advBalanceService.backOut(paramMap);

            return OK;
        }
    }

    /**
     * 广告主充值的充值记录导出excel功能
     * 
     * @param request
     * @param response
     * @param paramMap
     *            这里用来接收搜索的搜索条件，如果充值记录有搜索条件这时页面的数据也是按搜索条件查出来的那导出的excel数据也应该是搜索之后的数据
     */
    @RequestMapping("/exportExcel")
    public void exportFinanceListExcel(HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, Object> paramMap) {
        List<AdvBalance> advBalanceList = advBalanceService.findByParams(paramMap);

        response.reset();
        // Content-Type:application/vnd.ms-excel;charset=utf8或者text/xml;charset=utf8
        response.setContentType("application/vnd.ms-excel;charset=utf8");
        // 设置excel文件名称
        SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "report" + df2.format(new Date());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        // 需要对excel的列的总数进行指定
        int column = 6;
        paramMap.put("dataSize", (advBalanceList.size() + 100));
        paramMap.put("column", column);
        paramMap.put("dataList", advBalanceList);

        String excelTemplate = templateProcessor.processTemplate("excel/deposit.ftl", paramMap);
        try {
            PrintWriter out = response.getWriter();
            out.write(excelTemplate);
            out.flush();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}
